import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import request from '@/unti/request'
import type { User } from '@/types/user.ts'

interface LoginForm {
  username: string
  password: string
}

interface RegisterForm {
  username: string
  password: string
  email?: string
  phonenumber?: string
}

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(localStorage.getItem('token'))
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const login = async (loginForm: LoginForm) => {
    try {
      const response = await request.post('/user/login/', loginForm)
      if (response.data.code === 200) {
        const { token: jwtToken, user: userInfo } = response.data
        token.value = jwtToken
        user.value = userInfo
        localStorage.setItem('token', jwtToken)
        
        return { success: true, message: response.data.message }
      } else {
        return { success: false, message: response.data.message }
      }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.message || '登录失败，请稍后重试'
      }
    }
  }

  // 注册
  const register = async (registerForm: RegisterForm) => {
    try {
      console.log("registerForm:",registerForm)
      const response = await request.post('api/user/register/', registerForm)
      if (response.data.code === 200) {
        return { success: true, message: response.data.message }
      } else {
        return { success: false, message: response.data.message }
      }
    } catch (error: any) {
      return { 
        success: false, 
        message: error.message || '注册失败，请稍后重试'
      }
    }
  }

  // 登出
  const logout = async () => {
    try {
      await request.post('/user/logout/')
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 无论登出请求是否成功，都清除本地状态
      token.value = null
      user.value = null
      localStorage.removeItem('token')
    }
  }

  // 获取用户信息
  const fetchUserInfo = async () => {
    if (!token.value) return
    
    try {
      const response = await request.get('/user/info/')
      if (response.data.code === 200) {
        user.value = response.data
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，清除登录状态
      await logout()
    }
  }

  // 初始化
  const initAuth = () => {
    if (token.value) {
      fetchUserInfo()
    }
  }

  return {
    user,
    token,
    isLoggedIn,
    login,
    register,
    logout,
    fetchUserInfo,
    initAuth
  }
})